package utils;

import java.util.ArrayList;
import java.util.List;

import utils.StringUtils.MyStringBuffer;

public class NumberUtils {

	
	public static String formatSize(int size){
		int K = 1024;
		int M = 1048576;
		
		if(size >= M){
			return formatSize_MB(size);
		}else if(size >= K){
			return formatSize_KB(size);
		}else{
			return formatSize_B(size);
		}
	}
	
	private static String formatSize_B(int size){
		MyStringBuffer msb = StringUtils.getNewMyStringBuffer();
		msb.put(format(size)).put(" Byte");
		
		return msb.getStringAndClose();
	}
	/**
	 * divide the size with 1024
	 * @param size
	 * @return
	 */
	private static String formatSize_KB(int size){
		MyStringBuffer msb = StringUtils.getNewMyStringBuffer();
		int K = 1024;
		int factor = 1;
		
		if(size>100*K){
			factor = 1;
		}else if(size>10*K) {
			factor = 10;
		}else {
			factor = 100;
		}
		
		double d = size*(factor*1.0)/K;
		int temp = (int) d;
		d = temp/(factor*1.0);
		if(factor==1){
			msb.put(temp);
		}else{
			msb.put(d);
		}
		msb.put(" KB");
		return msb.getStringAndClose();
	}
	private static String formatSize_MB(int size){
		MyStringBuffer msb = StringUtils.getNewMyStringBuffer();
		int M = 1024*1024;
		int factor = 1;
		
		if(size>100*M){
			factor = 1;
		}else if(size>10*M) {
			factor = 10;
		}else {
			factor = 100;
		}
		
		double d = size*(factor*1.0)/M;
		int temp = (int) d;
		d = temp/(factor*1.0);
		if(factor==1){
			msb.put(temp);
		}else{
			msb.put(d);
		}
		msb.put(" MB");
		return msb.getStringAndClose();
	}
	
	/**
	 * format a number like this: ##,###,###
	 * @param size
	 * @return
	 */
	private static String format(int size) {
		NumberFormatStack stack = new NumberFormatStack();
		while(size>0){
			int n = size%10;
			size = size /10;
			stack.push(n);
		}
		return stack.format();
	}
	
	private static class NumberFormatStack{
		private List<Object> list= new ArrayList<Object>();
		
		private int index;
		
		public NumberFormatStack push(Object obj){
			if(index%3==0 && index!=0)list.add(",");
			list.add(obj);
			index++;
			return this;
		}
		public Object pop(){
			if(list.size()==0) return null;
			return list.remove(list.size()-1);
		}
		public String format(){
			MyStringBuffer msb = StringUtils.getNewMyStringBuffer();
			Object obj = null;
			while((obj = pop())!=null){
				msb.put(obj.toString());
			}
			return msb.getStringAndClose();
		}
	}
}
